// filename: MessagePumpForUI.cpp
// author: enic
// date: 2015-10-09

#include "MessagePumpForUI.h"

#include <Windows.h>
#include <base/strings/tstring.h>
#include <string>
#include <thread>


MessagePumpForUI::MessagePumpForUI()
	: m_atom(0), m_hMessageWnd(NULL)
{

}

MessagePumpForUI::~MessagePumpForUI()
{

}

void MessagePumpForUI::DoRunLoop()
{
	while (true)
	{
		bool bMoreWorkIsPlausible = ProcessNextWindowsMessage();
		if (m_pState->bShouldQuit)
		{
			break;
		}

		bMoreWorkIsPlausible |= m_pState->pDelegate->DoWork();
		if (m_pState->bShouldQuit)
		{
			break;
		}

		bMoreWorkIsPlausible |= m_pState->pDelegate->DoDelayedWork(m_DelayedWorkTime);
		
		if (bMoreWorkIsPlausible && (0 == m_DelayedWorkTime))
		{
			KillTimer(m_hMessageWnd, reinterpret_cast<UINT_PTR>(this));
		}

		if (m_pState->bShouldQuit)
		{
			break;
		}

		if (bMoreWorkIsPlausible)
		{
			continue;
		}

		bMoreWorkIsPlausible = m_pState->pDelegate->DoIdelWork();
		if (m_pState->bShouldQuit)
		{
			break;
		}
			
		if (bMoreWorkIsPlausible)
		{
			continue;
		}

		WaitForWork();
	}
}

void MessagePumpForUI::InitMessageWnd()
{
	std::thread::id thisTID = std::this_thread::get_id();
	std::tstring strName = /*Guid::GenGuid().tou16string()*/ _T("third_id");

	HINSTANCE hInstance = GetModuleHandle(NULL);

	WNDCLASSEX wc = { 0 };
	wc.cbSize = sizeof(wc);
	wc.lpfnWndProc = MessagePumpForUI::__MessageWndProc;
	wc.hInstance = hInstance;
	wc.lpszClassName = strName.c_str();
	m_atom = RegisterClassEx(&wc);

	DCHECK(m_atom);

	m_hMessageWnd = CreateWindow(MAKEINTATOM(m_atom), 0, 0, 0, 0, 0, 0,
		HWND_MESSAGE, 0, hInstance, 0);

	DCHECK(m_hMessageWnd);
}

bool MessagePumpForUI::ProcessNextWindowsMessage()
{

}

bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg)
{

}

bool MessagePumpForUI::ProcessPumpReplacementMessage()
{

}


LRESULT CALLBACK MessagePumpForUI::__MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
	return DefWindowProc(hwnd, message, wparam, lparam);
}


